﻿using System;

namespace ConsoleOldToNew
{
    class CrcCheck
    {

        //获取校验码
        public static string GetCRC16(string strTest)
        {
            try
            {
                int wkg = 0xffff;
                byte[] bytes = GetGeneralByteArray(strTest);

                for (int i = 0; i < bytes.Length; i++)
                {
                    byte b = bytes[i];
                    wkg = (wkg >> 8) & 0x00ff;
                    wkg ^= b;

                    for (int j = 0; j < 8; j++)
                    {
                        if ((wkg & 0x0001) == 1)
                        {
                            wkg = (wkg >> 1) ^ 0xa001;
                        }
                        else
                        {
                            wkg = wkg >> 1;
                        }
                    }


                }
                return Convert.ToString((wkg), 16).ToUpper().PadLeft(4, '0');
            }
            catch
            {
                return "";
            }
        }
        /// <summary>
        /// 得到通用的字节数组
        /// </summary>
        /// <param name="arrayLength"></param>
        /// <param name="strArrayValue"></param>
        /// <returns></returns>
        private static byte[] GetGeneralByteArray(string strArrayValue)
        {
            char[] charArrayValue = strArrayValue.ToCharArray();
            byte[] generalByteArray = new byte[charArrayValue.Length];

            for (int i = 0; i < charArrayValue.Length; i++)
            {

                generalByteArray[i] = Convert.ToByte(charArrayValue[i]);

            }
            return generalByteArray;
        }
    }
}
